/*
 * Copyright（C） 2021 Huawei Device Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.roughike.bottombar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Optional;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;

import ohos.agp.components.AttrHelper;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;

/**
 * 资源文件工具类
 */
public class ResHelper {
    private static final Logger logger = Logger.getLogger("ResHelper");

    /**
     * 获取资源文件中的color值
     *
     * @param context context {@link Context}
     * @param resId   资源id
     * @return color
     */
    public static int getColor(Context context, int resId) {
        try {
            return ResHelper.getElement(context, resId).getColor();
        } catch (IOException | WrongTypeException | NotExistException e) {
            logger.log(Level.INFO, e.getMessage());
        }
        return -1;
    }

    /**
     * 获取资源文件中的string值
     *
     * @param context context {@link Context}
     * @param resId   资源id
     * @return string
     */
    public static String getString(Context context, int resId) {
        try {
            return ResHelper.getElement(context, resId).getString();
        } catch (IOException | WrongTypeException | NotExistException e) {
            logger.log(Level.INFO, e.getMessage());
        }
        return null;
    }

    /**
     * 获取integer.json中的数值
     *
     * @param context context {@link Context}
     * @param resId   资源id
     * @return int
     */
    public static int getDimension(Context context, int resId) {
        try {
            return ResHelper.getElement(context, resId).getInteger();
        } catch (IOException | WrongTypeException | NotExistException e) {
            logger.log(Level.INFO, e.getMessage());
        }
        return Integer.MAX_VALUE;
    }

    private static ohos.global.resource.Element getElement(Context context, int resId)
            throws NotExistException, WrongTypeException, IOException {
        return context.getResourceManager().getElement(resId);
    }

    /**
     * convert rawfile to {@link File} obj
     *
     * @param context {@link Context}
     * @param resPath eg:"resources/rawfile/abc.ttf"
     * @return a {@link File} obj
     */
    public static File resPathToFile(Context context, String resPath) {
        String[] fileNames = resPath.split("/");
        File tempFile = new File(context.getCacheDir() + File.separator + fileNames[fileNames.length - 1]);
        if (tempFile.exists() && tempFile.length() != 0) {
            return tempFile;
        }
        Resource resource = null;
        FileOutputStream fos = null;
        try {
            ResourceManager resourceManager = context.getResourceManager();
            resource = resourceManager.getRawFileEntry(resPath).openRawFile();
            byte[] buffer = new byte[resource.available()];
            resource.read(buffer);
            fos = new FileOutputStream(tempFile);
            fos.write(buffer);
        } catch (Exception e) {
            logger.log(Level.INFO, e.getMessage());
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (resource != null) {
                    resource.close();
                }
            } catch (IOException e) {
                logger.log(Level.INFO, e.getMessage());
            }

        }
        return tempFile;
    }

    /**
     * Converts dps to pixels nicely.
     *
     * @param context the Context for getting the resources
     * @param dp      dimension in dps
     * @return dimension in pixels
     */
    public static int dpToPixel(Context context, float dp) {
        return AttrHelper.vp2px(dp, context);
    }

    /**
     * Converts pixels to dps just as well.
     *
     * @param context the Context for getting the resources
     * @param px      dimension in pixels
     * @return dimension in dps
     */
    public static int pixelToDp(Context context, float px) {
        final float scale = context.getResourceManager().getDeviceCapability().screenDensity / 160f;
        return (int) (px / scale + 0.5f);
    }

    /**
     * Returns screen width.
     *
     * @param context Context to get resources and device specific display metrics
     * @return screen width(vp)
     */
    public static int getScreenWidth(Context context) {
        DisplayManager displayManager = DisplayManager.getInstance();
        Optional<Display> defaultDisplay = displayManager.getDefaultDisplay(context);
        DisplayAttributes displayAttributes = defaultDisplay.get().getRealAttributes();
        return pixelToDp(context, displayAttributes.width);
    }

    /**
     * invoke the resId of app bundle
     *
     * @param context      for get  package name
     * @param referenceStr for example {$media:i0_selected}
     * @return resource id
     */
    public static int invokeResId(Context context, String referenceStr) {
        String[] split = referenceStr.split(":");
        String type = split[0].substring(1);
        String fieldName = type.substring(0, 1).toUpperCase(Locale.ROOT) + type.substring(1) + "_" + split[1];
        try {
            Class<?> aClass = Class.forName(context.getBundleName() + ".ResourceTable");
            Field field = aClass.getDeclaredField(fieldName);
            return field.getInt(null);
        } catch (Exception e) {
            logger.log(Level.INFO, e.getMessage());
        }
        return -1;
    }
}
